package com.abe.mvp.view.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.abe.config.Constants;
import com.abe.mvp.contact.SerialPortContact;
import com.abe.mvp.contact.SocketContact;
import com.abe.mvp.model.bean.MainExerciseBean;
import com.abe.mvp.model.bean.exercise.ExerciseSTGroupBean;
import com.abe.mvp.model.bean.exercise.ExerciseSTNodeBean;
import com.abe.mvp.view.activity.base.BaseActivity;
import com.abe.mvp.view.adapter.MainExerciseInfoAdapter;
import com.abe.strengthtrainer.R;
import com.abe.utils.NormalUtils;
import com.abe.view.arcprogress.ArcProgress;

@ContentView(R.layout.activity_st_main_progress)
public abstract class MainProgressViewActivity extends BaseActivity implements
		SerialPortContact.View, SocketContact.View {

	/** 运动状态 */
	protected boolean isExercise = false;
	/** 锻炼器材上限 */
	protected int maxHeight = 600;
	/** 锻炼器材设置的最大幅度（用来转换小球屏幕位置） */
	protected int customMaxHeight = 0;
	protected int currentCustomHeight = 0;
	/** 锻炼器材设置的重量 */
	protected int oldCustomWeight = 0;
	protected int currentCustomWeight = 0;
	/** 重量变化节点 */
	protected List<ExerciseSTNodeBean> nodeBeans;
	/** 锻炼数据展示 */
	protected List<MainExerciseBean> exerciseBeans;
	/** 数据读取频率(ms) */
	protected static int readDataRate = 20;
	/** 锻炼数据 */
	protected ExerciseSTGroupBean groupBean;
	/** 锻炼时间（开始，结束，当前） */
	protected long exerciseStartTime = 0, exerciseStopTime = 0,
			currentTime = 0;
	protected Timer timer;
	/** 锻炼次数计数 */
	protected int currentCount = 0;
	/** 锻炼次数计数标识 */
	protected int wt_record_flg = 0;

	/** 启动成功 */
	public abstract void startSuccess();

	/** 停止成功 */
	public abstract void stopSuccess();

	/** 发送串口命令 */
	public abstract void sendSericalPortCommand(byte[] command);

	protected List<Integer> heights = new ArrayList<Integer>();
	protected List<Integer> times = new ArrayList<Integer>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		show_exercise_progress.setProgress(0);
		show_exercise_arc_progress.setRadius((int) (150 * scale));
		show_exercise_arc_progress.setProgress(0);
	}

	private void initData() {
		show_exercise_button_back.setVisibility(View.VISIBLE);
		/** 状态初始化 */
		isExercise = false;
		groupBean = new ExerciseSTGroupBean();
		nodeBeans = new ArrayList<ExerciseSTNodeBean>();
		exerciseBeans = new ArrayList<MainExerciseBean>();
		int[] names = { R.string.common_time, R.string.common_count,
				R.string.common_weight, R.string.common_calorie };
		int[] values = { 0, 0, 0, 0 };
		for (int i = 0; i < 4; i++) {
			MainExerciseBean exerciseBean = new MainExerciseBean();
			exerciseBean.setName(NormalUtils.getString(names[i]));
			exerciseBean.setData(String.valueOf(values[i]));
			exerciseBeans.add(exerciseBean);
		}
		adapter = new MainExerciseInfoAdapter(this, exerciseBeans, scale);
		LayoutParams params = show_exercise_info_grid.getLayoutParams();
		params.width = (int) (scale * 300 * exerciseBeans.size());
		show_exercise_info_grid.setLayoutParams(params);
		show_exercise_info_grid.setAdapter(adapter);
	}

	/** 根据高度变化更新次数 */
	protected void refreshCount() {
		switch (wt_record_flg) {
		case 0:
			if (currentCustomHeight >= 300) {
				wt_record_flg = 1;
			}
			break;
		case 1:
			if (currentCustomHeight <= 200) {
				currentCount++;
				/** 更新次数 */
				localCustomSendMessage(MAIN_REFRESH_COUNT, currentCount);
				wt_record_flg = 0;
			}
			break;
		}
	}

	/** 实时更新组数据 */
	protected void refreshExerciseGroupData(int count) {
		groupBean = new ExerciseSTGroupBean();
		/** 平均重量 */
		int weight = 0;
		int lastWeight = 0;
		float calorie = 0;
		int nodeSize = nodeBeans.size();
		if (nodeSize == 0) {
			count = 0;
		} else if (nodeSize == 1) {
			weight = nodeBeans.get(0).getNodeWeight();
			calorie = Constants.getKcal(weight,
					(float) (customMaxHeight / (float) 1000.0), count);
			lastWeight = weight;
		} else {
			for (int i = 1; i < nodeSize; i++) {
				ExerciseSTNodeBean temPreviousBean = nodeBeans.get(i - 1);
				ExerciseSTNodeBean temBean = nodeBeans.get(i);
				int temWeight = (temBean.getNodeCount() - temPreviousBean
						.getNodeCount()) * temPreviousBean.getNodeWeight();
				if (temWeight > 0) {
					weight = weight + temWeight;
				}
				if (i == nodeSize - 1) {
					temWeight = (count - temBean.getNodeCount())
							* temBean.getNodeWeight();
					weight = weight + temWeight;
				}
			}
			if (count != 0) {
				weight = weight / count;
			}
			calorie = Constants.getKcal(weight,
					(float) (customMaxHeight / (float) 1000.0), count);
			lastWeight = nodeBeans.get(nodeSize - 1).getNodeWeight();
		}
		groupBean.setCount(count);
		groupBean.setWeight(lastWeight);
		groupBean.setCalorie(calorie);
	}

	protected TimerTask task = new TimerTask() {
		@Override
		public void run() {
			currentTime = System.currentTimeMillis();
			localCustomSendMessage(
					MAIN_REFRESH_TIME,
					Constants
							.formatTime((int) ((currentTime - exerciseStartTime) / 1000)));
		}
	};

	@Event(value = R.id.show_exercise_button_back, type = View.OnClickListener.class)
	private void back(View view) {
		isExercise = false;
		stopSuccess();
	}

	/** 刷新时间 */
	protected static final int MAIN_REFRESH_TIME = 0x901;
	/** 刷新卡路里 */
	protected static final int MAIN_REFRESH_KAL = 0x902;
	/** 刷新重量 */
	protected static final int MAIN_REFRESH_WEIGHT = 0x903;
	/** 刷新次数 */
	protected static final int MAIN_REFRESH_COUNT = 0x904;
	/** 刷新进度条 */
	protected static final int MAIN_REFRESH_PROGRESS = 0x905;
	/** 发 */
	protected static final int MAIN_REFRESH_SEND = 0x906;
	/** 收 */
	protected static final int MAIN_REFRESH_RECEIVE = 0x907;

	protected void localCustomSendEmptyMessage(int what) {
		new CustomHander(Looper.getMainLooper()).sendEmptyMessage(what);
	}

	protected void localCustomSendMessage(int what, Object object) {
		new CustomHander(Looper.getMainLooper()).sendMessage(NormalUtils
				.getMessage(what, object));
	}

	class CustomHander extends Handler {
		public CustomHander(Looper looper) {
			super(looper);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {

			case MAIN_REFRESH_KAL: {
				MainExerciseBean temBean = exerciseBeans.get(3);
				temBean.setData(String.valueOf((int) groupBean.getCalorie()));
				exerciseBeans.set(3, temBean);
				adapter.notifyDataSetChanged();
			}
			case MAIN_REFRESH_WEIGHT: {
				MainExerciseBean temBean = exerciseBeans.get(2);
				temBean.setData(String.valueOf(currentCustomWeight));
				exerciseBeans.set(2, temBean);
				adapter.notifyDataSetChanged();
			}
				break;
			case MAIN_REFRESH_COUNT: {
				MainExerciseBean temBean = exerciseBeans.get(1);
				temBean.setData(msg.obj.toString());
				exerciseBeans.set(1, temBean);
				adapter.notifyDataSetChanged();
			}
				break;
			case MAIN_REFRESH_TIME: {
				MainExerciseBean temBean = exerciseBeans.get(0);
				temBean.setData(msg.obj.toString());
				exerciseBeans.set(0, temBean);
				adapter.notifyDataSetChanged();
			}
			case MAIN_REFRESH_PROGRESS:
				heights.add(currentCustomHeight);
				float rate = (float) currentCustomHeight / (float) maxHeight;
				int progress = (int) (rate * 100);
				show_exercise_progress.setProgress(progress);
				show_exercise_arc_progress.setProgress(progress);
				break;
			case MAIN_REFRESH_SEND:
				show_message_01.setText(msg.obj.toString());
				break;
			case MAIN_REFRESH_RECEIVE:
				show_message_02.setText(msg.obj.toString());
				break;
			}
		}
	}

	@ViewInject(R.id.show_message_01)
	protected TextView show_message_01;
	@ViewInject(R.id.show_message_02)
	protected TextView show_message_02;
	@ViewInject(R.id.show_exercise_button_back)
	protected LinearLayout show_exercise_button_back;

	@ViewInject(R.id.move_cure_layout)
	protected LinearLayout move_cure_layout;
	@ViewInject(R.id.show_exercise_progress)
	protected ProgressBar show_exercise_progress;
	@ViewInject(R.id.show_exercise_arc_progress)
	protected ArcProgress show_exercise_arc_progress;
	@ViewInject(R.id.show_exercise_info_grid)
	protected GridView show_exercise_info_grid;
	protected MainExerciseInfoAdapter adapter;

	/********************************* 串口相关 **************************************/

	@Override
	public void onConnectSuccess() {

	}

	@Override
	public void onCloseSuccess() {

	}

	@Override
	public void onSendDataSuccess() {

	}

	@Override
	public void onError(String errorMsg) {

	}

	/********************************** socket相关 *************************************/

	@Override
	public void onSocketConnectSuccess() {

	}

	@Override
	public void onSocketCloseSuccess() {

	}

	@Override
	public void onSocketSendDataSuccess() {

	}

	@Override
	public void onSocketReceiveDataSuccess(String receiveMsg) {

	}
}
